<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>七星彩助手 - 智能预测系统</title>
    <link href="https://unpkg.com/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.plot.ly/plotly-2.26.0.min.js"></script>
    <style>
        :root {
            --primary-color: #4f46e5;
            --secondary-color: #06b6d4;
            --success-color: #10b981;
            --warning-color: #f59e0b;
            --danger-color: #ef4444;
            --dark-color: #1f2937;
            --light-color: #f8fafc;
            --qxc-color: #ff6b35;
        }
        
        body {
            background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .navbar {
            background: rgba(255, 255, 255, 0.95) !important;
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
        }
        
        .card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border: none;
            border-radius: 15px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }
        
        .qxc-digit {
            width: 45px;
            height: 45px;
            border-radius: 8px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 18px;
            margin: 3px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
            background: linear-gradient(135deg, var(--qxc-color), #e55a2b);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--qxc-color), #e55a2b);
            border: none;
            border-radius: 25px;
            padding: 10px 30px;
            font-weight: 600;
        }
        
        .stats-card {
            background: linear-gradient(135deg, var(--qxc-color), #e55a2b);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .loading {
            display: none;
        }
        
        .loading.show {
            display: block;
        }
        
        .prediction-result {
            background: linear-gradient(135deg, #10b981, #059669);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin: 20px 0;
            text-align: center;
        }
        
        .chart-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin: 20px 0;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }
        
        .history-table {
            background: white;
            border-radius: 15px;
        }
        
        .batch-prediction-results {
            max-height: 600px;
            overflow-y: auto;
        }
        
        .method-results {
            background: rgba(255, 255, 255, 0.9);
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            border-left: 4px solid var(--qxc-color);
        }
        
        .method-title {
            color: var(--qxc-color);
            font-weight: bold;
            margin-bottom: 15px;
            padding-bottom: 8px;
            border-bottom: 2px solid rgba(255, 107, 53, 0.2);
        }
        
        .single-prediction {
            background: rgba(255, 255, 255, 0.8);
            border-radius: 8px;
            padding: 12px;
            border: 1px solid rgba(255, 107, 53, 0.2);
        }
        
        .prediction-header {
            font-weight: bold;
            color: var(--dark-color);
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .confidence-info {
            font-size: 12px;
            color: var(--success-color);
            font-weight: bold;
        }
        
        .position-label {
            font-size: 11px;
            color: #666;
            font-weight: 500;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }
        
        .table th {
            background: var(--qxc-color);
            color: white;
            border: none;
            font-weight: 600;
        }
        
        .confidence-badge {
            background: linear-gradient(135deg, var(--success-color), #059669);
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.9em;
            font-weight: 600;
        }
        
        .feature-icon {
            font-size: 3rem;
            color: var(--qxc-color);
            margin-bottom: 20px;
        }
        
        .qxc-header {
            background: linear-gradient(135deg, var(--qxc-color), #e55a2b);
        }
        

        
        .position-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light fixed-top">
        <div class="container">
            <a class="navbar-brand fw-bold" href="#">
                <i class="fas fa-star text-warning me-2"></i>
                七星彩助手
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="#prediction">智能预测</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#history">历史数据</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#statistics">数据分析</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container" style="margin-top: 100px;">
        <!-- 欢迎区域 -->
        <div class="row mb-5">
            <div class="col-12 text-center text-white">
                <h1 class="display-4 fw-bold mb-3">⭐ 七星彩智能助手</h1>
                <p class="lead">基于大数据分析和机器学习算法，专业预测七星彩中奖号码</p>
                <p class="text-light">海南七星彩 • 每周二、五、日开奖</p>
            </div>
        </div>

        <!-- 功能卡片 -->
        <div class="row mb-5">
            <div class="col-md-4 mb-4">
                <div class="card h-100 text-center">
                    <div class="card-body">
                        <i class="fas fa-brain feature-icon"></i>
                        <h5 class="card-title">智能预测</h5>
                        <p class="card-text">运用多种算法分析七星彩历史数据，预测下期7位数字</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4 mb-4">
                <div class="card h-100 text-center">
                    <div class="card-body">
                        <i class="fas fa-chart-line feature-icon"></i>
                        <h5 class="card-title">位置分析</h5>
                        <p class="card-text">深度分析每个位置数字的出现规律和变化趋势</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4 mb-4">
                <div class="card h-100 text-center">
                    <div class="card-body">
                        <i class="fas fa-history feature-icon"></i>
                        <h5 class="card-title">实时数据</h5>
                        <p class="card-text">实时爬取海南七星彩官方开奖数据，保持数据最新</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 预测区域 -->
        <div id="prediction" class="row mb-5">
            <div class="col-12">
                <div class="card">
                    <div class="card-header qxc-header text-white">
                        <h4 class="mb-0"><i class="fas fa-magic me-2"></i>七星彩智能预测</h4>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <!-- 预测模式选择 -->
                                <div class="mb-3">
                                    <h5>预测模式</h5>
                                    <div class="btn-group w-100" role="group">
                                        <input type="radio" class="btn-check" name="predictionMode" id="singleMode" value="single" checked>
                                        <label class="btn btn-outline-primary" for="singleMode">单一预测</label>
                                        
                                        <input type="radio" class="btn-check" name="predictionMode" id="batchMode" value="batch">
                                        <label class="btn btn-outline-primary" for="batchMode">批量预测</label>
                                    </div>
                                </div>
                                
                                <!-- 单一预测模式 -->
                                <div id="singlePredictionPanel">
                                    <h5>选择预测方法</h5>
                                    <select class="form-select mb-3" id="predictionMethod">
                                        <option value="ensemble">集成算法（推荐）</option>
                                        <option value="frequency">频率分析</option>
                                        <option value="pattern">模式分析</option>
                                        <option value="ml">机器学习</option>
                                        <option value="hot_cold">冷热号分析</option>
                                        <option value="position">位置分析</option>
                                        <option value="min_frequency">最低频率分析</option>
                                    </select>
                                    
                                    <button class="btn btn-primary btn-lg w-100" onclick="predictNumbers()">
                                        <i class="fas fa-wand-magic me-2"></i>开始预测七星彩
                                    </button>
                                </div>
                                
                                <!-- 批量预测模式 -->
                                <div id="batchPredictionPanel" style="display: none;">
                                    <h5>选择预测算法（可多选）</h5>
                                    <div class="mb-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="ensemble" id="method_ensemble" checked>
                                            <label class="form-check-label" for="method_ensemble">集成算法（推荐）</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="frequency" id="method_frequency">
                                            <label class="form-check-label" for="method_frequency">频率分析</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="pattern" id="method_pattern">
                                            <label class="form-check-label" for="method_pattern">模式分析</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="ml" id="method_ml">
                                            <label class="form-check-label" for="method_ml">机器学习</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="hot_cold" id="method_hot_cold">
                                            <label class="form-check-label" for="method_hot_cold">冷热号分析</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="position" id="method_position">
                                            <label class="form-check-label" for="method_position">位置分析</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" value="min_frequency" id="method_min_frequency">
                                            <label class="form-check-label" for="method_min_frequency">最低频率分析</label>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="predictionCount" class="form-label">每种算法预测组数</label>
                                        <select class="form-select" id="predictionCount">
                                            <option value="1">1组</option>
                                            <option value="2">2组</option>
                                            <option value="3" selected>3组</option>
                                            <option value="5">5组</option>
                                        </select>
                                    </div>
                                    
                                    <button class="btn btn-success btn-lg w-100" onclick="batchPredictNumbers()">
                                        <i class="fas fa-layer-group me-2"></i>批量预测七星彩
                                    </button>
                                </div>
                                
                                <div class="alert alert-info mt-3">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>七星彩中奖规则：</strong>
                                    <br>• 一等奖：7位全中（浮动奖金，最高500万）
                                    <br>• 二等奖：前6位或后6位全中（浮动奖金）
                                    <br>• 三等奖：前5位或后5位全中（3000元）
                                    <br>• 四等奖：前4位或后4位全中（500元）
                                    <br>• 五等奖：前3位或后3位全中（30元）
                                    <br>• 六等奖：前2位或后2位全中（5元）
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div id="predictionResult"></div>
                                <div id="loadingPrediction" class="loading text-center">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">预测中...</span>
                                    </div>
                                    <p class="mt-2">正在分析七星彩数据，请稍候...</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 历史数据区域 -->
        <div id="history" class="row mb-5">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h4 class="mb-0"><i class="fas fa-database me-2"></i>七星彩历史开奖数据</h4>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div class="dropdown">
                                <button class="btn btn-primary dropdown-toggle" type="button" id="updateDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                    <i class="fas fa-sync-alt me-2"></i>更新数据
                                </button>
                                <ul class="dropdown-menu" aria-labelledby="updateDropdown">
                                    <li><a class="dropdown-item" href="javascript:void(0)" onclick="loadHistory()"><i class="fas fa-refresh me-2"></i>刷新显示</a></li>
                                    <li><a class="dropdown-item" href="javascript:void(0)" onclick="crawlData(false)"><i class="fas fa-download me-2"></i>获取新数据</a></li>
                                    <li><a class="dropdown-item" href="javascript:void(0)" onclick="crawlData(true)"><i class="fas fa-redo me-2"></i>强制重新获取</a></li>
                                </ul>
                            </div>
                            <div>
                                <span class="badge bg-primary">数据总数: <span id="dataCount">0</span></span>
                            </div>
                        </div>
                        <div id="historyTable" class="history-table">
                            <!-- 历史数据表格将在这里显示 -->
                        </div>
                        <div id="loadingHistory" class="loading text-center">
                            <div class="spinner-border text-info" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-2">正在加载七星彩历史数据...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 统计分析区域 -->
        <div id="statistics" class="row mb-5">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h4 class="mb-0"><i class="fas fa-chart-bar me-2"></i>七星彩数据统计分析</h4>
                    </div>
                    <div class="card-body">
                        <button class="btn btn-success mb-3" onclick="loadStatistics()">
                            <i class="fas fa-sync-alt me-2"></i>生成统计报告
                        </button>
                        <div id="statisticsContent">
                            <!-- 统计内容将在这里显示 -->
                        </div>
                        <div id="loadingStats" class="loading text-center">
                            <div class="spinner-border text-success" role="status">
                                <span class="visually-hidden">分析中...</span>
                            </div>
                            <p class="mt-2">正在生成七星彩统计分析...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-dark text-white text-center py-4 mt-5">
        <div class="container">
            <p>&copy; 2024 七星彩助手. 仅供娱乐参考，请理性购彩.</p>
        </div>
    </footer>

    <!-- JavaScript -->
    <script src="https://unpkg.com/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadHistory();
            loadStatistics();
            initializePredictionMode();
        });
        
        // 初始化预测模式切换
        function initializePredictionMode() {
            const singleModeRadio = document.getElementById('singleMode');
            const batchModeRadio = document.getElementById('batchMode');
            const singlePanel = document.getElementById('singlePredictionPanel');
            const batchPanel = document.getElementById('batchPredictionPanel');
            
            singleModeRadio.addEventListener('change', function() {
                if (this.checked) {
                    singlePanel.style.display = 'block';
                    batchPanel.style.display = 'none';
                    document.getElementById('predictionResult').innerHTML = '';
                }
            });
            
            batchModeRadio.addEventListener('change', function() {
                if (this.checked) {
                    singlePanel.style.display = 'none';
                    batchPanel.style.display = 'block';
                    document.getElementById('predictionResult').innerHTML = '';
                }
            });
        }
        
        // 批量预测功能
        async function batchPredictNumbers() {
            // 获取选中的算法
            const selectedMethods = [];
            const checkboxes = document.querySelectorAll('#batchPredictionPanel input[type="checkbox"]:checked');
            checkboxes.forEach(checkbox => {
                selectedMethods.push(checkbox.value);
            });
            
            if (selectedMethods.length === 0) {
                showError('请至少选择一种预测算法');
                return;
            }
            
            const count = parseInt(document.getElementById('predictionCount').value);
            
            showLoading('loadingPrediction');
            document.getElementById('predictionResult').innerHTML = '';
            
            try {
                const response = await fetch('/api/batch_predict', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        type: 'qxc',
                        methods: selectedMethods,
                        count: count
                    })
                });
                
                const data = await response.json();
                
                hideLoading('loadingPrediction');
                
                if (data.success) {
                    displayBatchPrediction(data);
                } else {
                    showError('批量预测失败: ' + data.error);
                }
            } catch (error) {
                hideLoading('loadingPrediction');
                showError('网络错误: ' + error.message);
            }
        }
        
        // 显示批量预测结果
        function displayBatchPrediction(data) {
            const resultDiv = document.getElementById('predictionResult');
            let html = '<div class="batch-prediction-results">';
            
            html += '<div class="prediction-result">';
            html += '<h5><i class="fas fa-layer-group me-2"></i>批量预测结果</h5>';
            html += `<p class="mb-3">共生成 <strong>${data.total_predictions}</strong> 组预测号码</p>`;
            html += '</div>';
            
            // 为每种算法显示结果
            data.batch_results.forEach(methodResult => {
                html += '<div class="method-results mb-4">';
                html += `<h6 class="method-title"><i class="fas fa-cog me-2"></i>${methodResult.method_name}</h6>`;
                
                methodResult.results.forEach(result => {
                    html += '<div class="single-prediction mb-3">';
                    html += `<div class="prediction-header">第 ${result.index} 组预测</div>`;
                    
                    // 显示位置标签
                    html += '<div class="mb-2">';
                    for (let i = 1; i <= 7; i++) {
                        html += `<span class="position-label" style="display: inline-block; width: 48px; text-align: center; font-size: 12px;">第${i}位</span>`;
                    }
                    html += '</div>';
                    
                    // 显示预测数字
                    html += '<div class="mb-2">';
                    if (result.prediction && result.prediction.prediction) {
                        const predictionNumbers = Array.isArray(result.prediction.prediction) ? 
                            result.prediction.prediction : 
                            (typeof result.prediction.prediction === 'string' ? 
                                result.prediction.prediction.split('') : []);
                        
                        for (let i = 0; i < predictionNumbers.length && i < 7; i++) {
                            const digit = predictionNumbers[i];
                            if (i === 6 && digit >= 10) {
                                html += `<span class="qxc-digit" style="width: 60px; height: 35px; font-size: 14px;">${digit}</span>`;
                            } else {
                                html += `<span class="qxc-digit" style="width: 45px; height: 35px; font-size: 14px;">${digit}</span>`;
                            }
                        }
                    }
                    html += '</div>';
                    
                    // 显示置信度
                    if (result.prediction && result.prediction.confidence) {
                        html += `<div class="confidence-info">置信度: ${Math.round(result.prediction.confidence * 100)}%</div>`;
                    }
                    
                    html += '</div>';
                });
                
                html += '</div>';
            });
            
            // 添加导出按钮
            html += '<div class="text-center mt-4">';
            html += '<button class="btn btn-info" onclick="exportBatchResults()">';
            html += '<i class="fas fa-download me-2"></i>导出预测结果';
            html += '</button>';
            html += '</div>';
            
            html += '</div>';
            
            resultDiv.innerHTML = html;
        }
        
        // 导出批量预测结果
        function exportBatchResults() {
            const batchResults = document.querySelector('.batch-prediction-results');
            if (!batchResults) {
                showError('没有可导出的预测结果');
                return;
            }
            
            let exportText = '七星彩批量预测结果\n';
            exportText += '生成时间: ' + new Date().toLocaleString() + '\n\n';
            
            // 获取所有方法结果
            const methodResults = document.querySelectorAll('.method-results');
            methodResults.forEach(methodDiv => {
                const methodTitle = methodDiv.querySelector('.method-title').textContent.trim();
                exportText += methodTitle + ':\n';
                
                const predictions = methodDiv.querySelectorAll('.single-prediction');
                predictions.forEach(predDiv => {
                    const header = predDiv.querySelector('.prediction-header').textContent.trim();
                    const digits = predDiv.querySelectorAll('.qxc-digit');
                    let numbers = [];
                    digits.forEach(digit => {
                        numbers.push(digit.textContent.trim());
                    });
                    const confidence = predDiv.querySelector('.confidence-info');
                    const confidenceText = confidence ? confidence.textContent.trim() : '';
                    
                    exportText += `  ${header}: ${numbers.join(' ')} (${confidenceText})\n`;
                });
                
                exportText += '\n';
            });
            
            // 创建下载链接
            const blob = new Blob([exportText], { type: 'text/plain;charset=utf-8' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `七星彩预测结果_${new Date().toISOString().slice(0, 10)}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
            
            showSuccess('预测结果已导出到文件');
        } // 预测号码
        async function predictNumbers() {
            const method = document.getElementById('predictionMethod').value;
            
            showLoading('loadingPrediction');
            document.getElementById('predictionResult').innerHTML = '';
            
            try {
                const response = await fetch(`/api/predict?type=qxc&method=${method}`);
                const data = await response.json();
                
                hideLoading('loadingPrediction');
                
                if (data.success) {
                    displayPrediction(data.prediction);
                } else {
                    showError('预测失败: ' + data.error);
                }
            } catch (error) {
                hideLoading('loadingPrediction');
                showError('网络错误: ' + error.message);
            }
        }

        // 显示预测结果
        function displayPrediction(prediction) {
            const resultDiv = document.getElementById('predictionResult');
            let html = '<div class="prediction-result pulse">';
            
            html += '<h5><i class="fas fa-star me-2"></i>七星彩预测结果</h5>';
            
            // 显示位置标签
            html += '<div class="mb-2">';
            for (let i = 1; i <= 7; i++) {
                html += `<span class="position-label" style="display: inline-block; width: 48px; text-align: center;">第${i}位</span>`;
            }
            html += '</div>';
            
            // 显示预测数字
            html += '<div class="mb-3">';
            if (prediction.prediction) {
                // 处理数字列表格式的预测结果
                const predictionNumbers = Array.isArray(prediction.prediction) ? prediction.prediction : 
                    (typeof prediction.prediction === 'string' ? prediction.prediction.split('') : []);
                
                for (let i = 0; i < predictionNumbers.length && i < 7; i++) {
                    const digit = predictionNumbers[i];
                    // 对于第7位数字，如果是两位数需要特殊处理显示
                    if (i === 6 && digit >= 10) {
                        html += `<span class="qxc-digit" style="width: 60px;">${digit}</span>`;
                    } else {
                        html += `<span class="qxc-digit">${digit}</span>`;
                    }
                }
            }
            html += '</div>';
            
            html += `<div class="mt-3">`;
            html += `<span class="confidence-badge">置信度: ${Math.round(prediction.confidence * 100)}%</span>`;
            html += `<small class="d-block mt-2 text-light">预测方法: ${getMethodName(prediction.method)}</small>`;
            html += `</div>`;
            html += '</div>';
            
            resultDiv.innerHTML = html;
        }
        
        // 获取方法中文名称
        function getMethodName(method) {
            const methodNames = {
                'ensemble': '集成算法',
                'frequency': '频率分析',
                'pattern': '模式分析',
                'ml': '机器学习',
                'hot_cold': '冷热号分析',
                'position': '位置分析',
                'min_frequency': '最低频率分析'
            };
            return methodNames[method] || method;
        }

        // 加载历史数据
        async function loadHistory() {
            showLoading('loadingHistory');
            
            try {
                const response = await fetch('/api/history?type=qxc&limit=10000');
                const data = await response.json();
                
                hideLoading('loadingHistory');
                
                if (data.success) {
                    displayHistory(data.data);
                    document.getElementById('dataCount').textContent = data.data.length;
                } else {
                    showError('加载历史数据失败: ' + data.error);
                }
            } catch (error) {
                hideLoading('loadingHistory');
                showError('网络错误: ' + error.message);
            }
        }

        // 显示历史数据
        function displayHistory(data) {
            const tableDiv = document.getElementById('historyTable');
            
            if (data.length === 0) {
                tableDiv.innerHTML = '<p class="text-center text-muted">暂无历史数据，请点击"更新数据"获取最新开奖信息</p>';
                return;
            }
            
            let html = '<table class="table table-striped table-hover">';
            html += '<thead><tr><th>期号</th><th>开奖日期</th><th>开奖号码</th></tr></thead>';
            html += '<tbody>';
            
            data.forEach(record => {
                html += '<tr>';
                html += `<td><strong>${record.period}</strong></td>`;
                html += `<td>${record.draw_date}</td>`;
                html += '<td>';
                
                if (record.numbers && record.numbers.length === 7) {
                    for (let i = 0; i < record.numbers.length; i++) {
                        html += `<span class="qxc-digit" style="width: 35px; height: 35px; font-size: 14px;">${record.numbers[i]}</span>`;
                    }
                }
                
                html += '</td>';
                html += '</tr>';
            });
            
            html += '</tbody></table>';
            tableDiv.innerHTML = html;
        }

        // 爬取数据
        async function crawlData(forceUpdate = false) {
            showLoading('loadingHistory');
            
            try {
                const periods = forceUpdate ? 100 : 10;
                const url = `/api/crawl?type=qxc&periods=${periods}&force_update=${forceUpdate}`;
                const response = await fetch(url);
                const data = await response.json();
                
                hideLoading('loadingHistory');
                
                if (data.success) {
                    showSuccess(data.message);
                    loadHistory(); // 重新加载历史数据
                } else {
                    showError('数据更新失败: ' + data.error);
                }
            } catch (error) {
                hideLoading('loadingHistory');
                showError('网络错误: ' + error.message);
            }
        }

        // 加载统计数据
        async function loadStatistics() {
            showLoading('loadingStats');
            
            try {
                const response = await fetch('/api/statistics?type=qxc');
                const data = await response.json();
                
                hideLoading('loadingStats');
                
                if (data.success) {
                    displayStatistics(data.statistics);
                } else {
                    showError('加载统计数据失败: ' + data.error);
                }
            } catch (error) {
                hideLoading('loadingStats');
                showError('网络错误: ' + error.message);
            }
        }

        // 显示统计数据
        function displayStatistics(stats) {
            const contentDiv = document.getElementById('statisticsContent');
            
            let html = '<div class="row">';
            
            // 基本统计信息
            html += '<div class="col-md-6 mb-4">';
            html += '<div class="stats-card">';
            html += '<h5><i class="fas fa-info-circle me-2"></i>基本信息</h5>';
            html += `<p>总期数: <strong>${stats.total_periods || 0}</strong></p>`;
            if (stats.date_range) {
                html += `<p>数据范围: ${stats.date_range.start} 至 ${stats.date_range.end}</p>`;
            }
            html += '</div>';
            html += '</div>';
            
            // 位置统计
            if (stats.position_stats) {
                html += '<div class="col-md-6 mb-4">';
                html += '<div class="stats-card">';
                html += '<h5><i class="fas fa-chart-bar me-2"></i>位置统计</h5>';
                html += `<p>最活跃位置: <strong>第${stats.position_stats.most_active_position}位</strong></p>`;
                html += `<p>平均和值: <strong>${stats.position_stats.average_sum}</strong></p>`;
                html += '</div>';
                html += '</div>';
            }
            
            // 数字分布
            if (stats.digit_distribution) {
                html += '<div class="col-md-12 mb-4">';
                html += '<div class="stats-card">';
                html += '<h5><i class="fas fa-chart-pie me-2"></i>数字分布统计</h5>';
                html += '<div class="row">';
                for (let digit = 0; digit <= 9; digit++) {
                    const count = stats.digit_distribution[digit] || 0;
                    html += '<div class="col-md-2 col-4 text-center mb-2">';
                    html += `<span class="qxc-digit" style="width: 40px; height: 40px;">${digit}</span>`;
                    html += `<div><small>${count}次</small></div>`;
                    html += '</div>';
                }
                html += '</div>';
                html += '</div>';
                html += '</div>';
            }
            
            html += '</div>';
            
            // 图表区域
            if (stats.charts) {
                html += '<div class="row">';
                Object.keys(stats.charts).forEach(chartKey => {
                    html += '<div class="col-md-6 mb-4">';
                    html += '<div class="chart-container">';
                    html += `<div id="chart-${chartKey}"></div>`;
                    html += '</div>';
                    html += '</div>';
                });
                html += '</div>';
            }
            
            contentDiv.innerHTML = html;
            
            // 渲染图表
            if (stats.charts) {
                renderCharts(stats.charts);
            }
        }

        // 渲染图表
        function renderCharts(charts) {
            Object.keys(charts).forEach(chartKey => {
                const chart = charts[chartKey];
                const elementId = `chart-${chartKey}`;
                
                if (chart.type === 'bar') {
                    Plotly.newPlot(elementId, [{
                        x: chart.data.x,
                        y: chart.data.y,
                        type: 'bar',
                        marker: { color: '#ff6b35' }
                    }], {
                        title: chart.data.title,
                        xaxis: { title: chart.data.xlabel || '数字' },
                        yaxis: { title: chart.data.ylabel || '出现次数' }
                    });
                } else if (chart.type === 'line') {
                    Plotly.newPlot(elementId, [{
                        x: chart.data.x,
                        y: chart.data.y,
                        type: 'scatter',
                        mode: 'lines+markers',
                        line: { color: '#ff6b35' }
                    }], {
                        title: chart.data.title,
                        xaxis: { title: chart.data.xlabel || '期号' },
                        yaxis: { title: chart.data.ylabel || '数值' }
                    });
                } else if (chart.type === 'pie') {
                    Plotly.newPlot(elementId, [{
                        labels: chart.data.labels,
                        values: chart.data.values,
                        type: 'pie'
                    }], {
                        title: chart.data.title
                    });
                }
            });
        }

        // 显示加载状态
        function showLoading(elementId) {
            document.getElementById(elementId).classList.add('show');
        }

        // 隐藏加载状态
        function hideLoading(elementId) {
            document.getElementById(elementId).classList.remove('show');
        }

        // 显示错误信息
        function showError(message) {
            alert('错误: ' + message);
        }

        // 显示成功信息
        function showSuccess(message) {
            alert('成功: ' + message);
        }
    </script>
</body>
</html>